package com.itSession.cn.controller;

import com.itSession.cn.exception.ResponseData;
import com.itSession.cn.util.DateUtils;
import com.itSession.cn.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Api(tags = "图片上传获取模块")
@RequestMapping({"/public"})
@Controller
public class PublicController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @RequestMapping(value = "/photoUpload", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData photoUpload(MultipartFile file, HttpServletRequest request,
                             HttpServletResponse response, HttpSession session) {

        ResponseData responseData = new ResponseData();
        // 判断上传的文件是否为空
        if (file != null) {
            // 文件路径
            String path = null;
            // 文件原名称
            String fileName = file.getOriginalFilename();
            // 文件类型
            String type = fileName.indexOf(".") != -1
                    ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            // 判断文件类型是否为空
            if (type != null) {
                if ("MP4".equals(type.trim().toUpperCase()) || "GIF".equals(type.trim().toUpperCase()) || "PNG".equals(type.toUpperCase())
                        || "JPG".equals(type.toUpperCase()) || "JPEG".equals(type.toUpperCase())) {
                    // 根路径
                    String realPath = uploadPath;
                    String trueFileName = DateUtils.getCurrentTimeMillis() + "." + type;
                    // 设置存放图片文件的路径(年月划分)
                    String imgPath = "/" + DateUtils.getYears() + "/" + DateUtils.getMonth()
                            + "/" + trueFileName;
                    responseData.data(imgPath);

                    path = realPath + imgPath;
                   /* String url = PublicController.class.getClassLoader().getResource("/").getPath().replace("%20", " ")
                            .replace('/', '\\');
                    String webinfUrl = url.substring(1, url.indexOf("classes") - 1);
                    path = webinfUrl + imgPath;*/
                    // 创建文件夹
                    if (!Tools.createFilePath(path)) {
                        return new ResponseData().fail(500, "文件夹创建失败");
                    }

                    try {
                        // 转存文件到指定的路径
                        file.transferTo(new File(path));
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    return new ResponseData().fail(500, "请上传GIF、PNG、JPG、JPEG、MP4格式文件");
                }
            } else {
                return new ResponseData().fail(500, "上传文件不合法");
            }
        } else {
            return new ResponseData().fail(500, "请选上传文件");
        }
        return responseData.success();
    }

    @RequestMapping(value = "/getImg", method = RequestMethod.GET)
    public void getImg(String path, HttpServletRequest request, HttpServletResponse httpResponse) {
        // 路径
        File file = new File(uploadPath + path);
        FileInputStream fis = null;
        try {
            // 文件类型
            String type = path.indexOf(".") != -1
                    ? path.substring(path.lastIndexOf(".") + 1, path.length()) : null;
            if ("MP4".equals(type.trim().toUpperCase())) {
                httpResponse.setContentType("video/mp4");
            } else {
                httpResponse.setContentType("image/gif");
            }
            OutputStream out = httpResponse.getOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];

            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "mp4", notes = "mp4")
    @GetMapping("/mp4")
    public void mp4(@ApiParam(value = "mp4路径") @RequestParam String path, HttpServletResponse response) {
        String file = this.uploadPath + path;
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            String diskfilename = "final.mp4";
            response.setContentType("video/mp4");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"");
            System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length - 1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            OutputStream os = response.getOutputStream();

            os.write(data);
            //先声明的流后关掉！
            os.flush();
            os.close();
            inputStream.close();

        } catch (Exception e) {

        }
    }
}
